var express = require('express');
var router = express.Router();
let db = require('../tools/DB');
let to = require('../tools/to');
let md5 = require('md5');
let uuid = require('uuid');
let jwt = require('jsonwebtoken');
let {
    SECRET
} = require('../tools/config');
let timeStamp = require('time-stamp');
let intercept = require('../tools/intercept')



//判断手机号是否存在
router.post('/isExist', async (req, res) => {

    let {
        tel
    } = req.body;

    let sql = "select tel from e_member where tel=?";
    let [err, result] = await to(db.query(sql, [tel]));

    if (result.length > 0) {
        res.json({
            code: 208,
            data: result,
            msg: '该用户已存在'
        })
    }

})


//会员注册的路由
router.post('/register', async (req, res) => {
    let {
        tel,
        pas
    } = req.body;
    //加密明文密码
    let pwd = md5(pas);
    let mid = uuid.v1();
    let sql = "insert into e_member(mid,tel,pas,createdate) values(?,?,?,?)";
    let [err, result] = await to(db.query(sql, [mid, tel, pwd, Date.now()]));
    if (!err) {
        if (result.affectedRows > 0) {
            res.json({
                code: 200,
                data: null,
                msg: '注册成功'
            })
        } else {
            res.json({
                data: err,
                msg: '注册不成功，请检查参数',
                code: 208
            })
        }
    } else {
        res.json({
            data: err,
            msg: '注册失败',
            code: 500
        })
    }
})

//会员登录的路由
router.post('/login', async (req, res) => {
    let {
        tel,
        pas
    } = req.body;
    let pwd = md5(pas);
    let sql = 'select * from e_member where tel=? and pas=?';
    let [err, result] = await to(db.query(sql, [tel, pwd]));
    if (!err) {
        if (result.length > 0) {
            //生成JSON web  token字符串
            let username = result[0].username;
            let photo = '/' + result[0].head_photo_url;
            let mid = result[0].mid;
            let exp = Date.now() + (1000 * 60 * 60 * 24 * 365); //token的过期时间
            let token = jwt.sign({
                mid,
                exp
            }, SECRET);
            res.json({
                code: 200,
                data: {
                    photo,
                    token,
                    username
                },
                msg: '登录成功'
            })
        } else {
            res.json({
                data: null,
                msg: '账号或者密码错误',
                code: 208
            })
        }
    } else {
        res.json({
            data: err,
            msg: '登录失败',
            code: 500
        })
    }
})
//token验证中间件，需要验证路由放在下面，不需要验证的路由放上面
router.use(intercept());
//课程报名
router.post('/study', async (req, res) => {
    let {
        cid,
        mid
    } = req.body;

    //查询数据库中的cid，如果重复的订单就提示用户订单已经提交，如果没有就往下执行
    let sql2 = "select cid from e_order where cid=?"
    let [err,result1] = await to(db.query(sql2, [cid]));
    console.log(result1);
    if (result1.length > 0) {
        res.json({
            code: 300,
            data: null,
            msg: '订单已存在，请勿重复报名'
        });
        return;
    } else {
        //生成订单id，年月日时分秒
        let oid = timeStamp('YYYYMMDDHHmmssms');
        let sql = "insert into e_order(oid,cid,mid,createdate,status) values(?,?,?,?,?)";
        let [err, result] = await to(db.query(sql, [oid, cid, mid, Date.now(), 1]))
        if (!err) {
            if (result.affectedRows > 0) {
                res.json({
                    code: 200,
                    data: null,
                    msg: '课程报名成功'
                })
            } else {
                res.json({
                    code: 208,
                    data: null,
                    msg: '不成功，请检查参数'
                })
            }

        } else {
            res.json({
                code: 500,
                data: null,
                msg: '课程报名失败'
            })

        }
    }


})


module.exports = router;